package com.selenium;

import com.alibaba.fastjson.JSONObject;
import com.selenium.bean.InitBean;
import com.selenium.bean.ThirdpartnarInitVO;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RequestCallback;

import java.lang.reflect.Field;
import java.time.Duration;
import java.util.*;


public class CookieUtils {

    public static String simpleCookie(Set<Cookie> cookies){
        StringBuffer buf = new StringBuffer();
        for(Cookie cookie:cookies){
            buf.append(cookie.getName()+"="+cookie.getValue()+";");
        }
        System.err.println("Cookie:"+buf);
        return buf.toString();
    }

    public static InitBean simpleCookiebean(String cookies){
        List<String> cookieList = new LinkedList<>();
        String[] arrs = cookies.split(";");
        ThirdpartnarInitVO vo = new ThirdpartnarInitVO();
        for(String str:arrs){
            String[] nameAndValue = str.split("=");

            String name = nameAndValue[0].trim();
            String value = nameAndValue.length>1?nameAndValue[1].trim():null;
            cookieList.add(str);
            setValue(vo,name.replace(".","_"),value);
        }
        InitBean initBean = new InitBean();
        initBean.setCookie(cookieList);
        initBean.setVo(vo);
        return initBean;
    }

    public static InitBean simpleCookiebean(Set<Cookie> cookies){
        List<String> cookieList = new LinkedList<>();
        ThirdpartnarInitVO vo = new ThirdpartnarInitVO();
        for(Cookie cookie:cookies){
            cookieList.add(cookie.getName()+"="+cookie.getValue());
            setValue(vo,cookie.getName().replace(".","_"),cookie.getValue());
        }
        InitBean initBean = new InitBean();
        initBean.setCookie(cookieList);
        initBean.setVo(vo);
        return initBean;
    }

    public static List<String> simpleCookieList(Set<Cookie> cookies){
        List<String> cookieList = new LinkedList<>();
        for(Cookie cookie:cookies){
            cookieList.add(cookie.getName()+"="+cookie.getValue());
        }
        return cookieList;
    }
    public static List<String> simpleCookieList(String cookies){
        String[] split = cookies.split(";");
        return Arrays.asList(split);
    }


//    public static HttpEntity HttpEntity(JSONObject json){
//        HttpHeaders httpHeaders = new HttpHeaders();
//        httpHeaders.add("Content-Type", "application/json");
//        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(json, httpHeaders);
//        return requestEntity;
//    }

    public static HttpHeaders HttpHeaders(Set<Cookie> token,MediaType mediaType){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put(HttpHeaders.COOKIE, simpleCookieList(token));
        httpHeaders.setContentType(mediaType);
        return httpHeaders;
    }

    public static HttpEntity HttpHeaders(Set<Cookie> token,MediaType mediaType,JSONObject json){
        HttpHeaders httpHeaders = HttpHeaders(token,mediaType);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(json, httpHeaders);
        return requestEntity;
    }

    public static HttpEntity HttpEntity(JSONObject json){
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(json, httpHeaders);
        return requestEntity;
    }

    /**
     * 显示等待
     * */
    public static WebElement wait(WebDriver driver, By by) {

        // 创建WebDriverWait实例，并设置等待时间
        Wait<WebDriver> wait = new FluentWait<>(driver)
                .withTimeout(Duration.ofSeconds(30))
                .pollingEvery(Duration.ofMillis(500))
                .ignoring(NoSuchElementException.class);
        WebElement ele = wait.until(ExpectedConditions.visibilityOfElementLocated(by));
        return ele;
    }

    /**
     * 显示等待
     * */
    public static Boolean waitBy(WebDriver driver, By by,String msg) {

        // 创建WebDriverWait实例，并设置等待时间
        Wait<WebDriver> wait = new FluentWait<>(driver)
                .withTimeout(Duration.ofSeconds(30))
                .pollingEvery(Duration.ofMillis(500))
                .ignoring(NoSuchElementException.class);
        return wait.until(ExpectedConditions.titleIs(msg));
    }

    /**
     * 显示等待
     * */
    public static WebElement wait(WebDriver driver, WebElement element) {

        // 创建WebDriverWait实例，并设置等待时间
        Wait<WebDriver> wait = new FluentWait<>(driver)
                .withTimeout(Duration.ofSeconds(30))
                .pollingEvery(Duration.ofMillis(500))
                .ignoring(NoSuchElementException.class);
        return wait.until(ExpectedConditions.visibilityOf(element));
    }



    public static <T> void setValue(T t, String fieldName, Object value) {
        System.err.println("设置值。name:"+fieldName+";value:"+value);
        try {

            //Class<T> tClass = (Class<T>) t.getClass();
            Field declaredField = t.getClass().getDeclaredField(fieldName);

            declaredField.setAccessible(true);
            declaredField.set(t, value);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("初始化："+fieldName+"失败："+e.getMessage());
        }
    }

}